package com.demo.blockchain.tool;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {
	private static ObjectMapper objectMapper;

	/**
	 * 将JSON字符串转化为Java对象
	 * @param jsonStr
	 * @param valueType
	 * @return Object
	 */
	public static <T> T jsonToObject(String jsonStr, Class<T> valueType) {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}

		try {
			return objectMapper.readValue(jsonStr, valueType);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	/**
	 * 将JSON数组转化为List集合对象
	 * @param jsonStr
	 * @param valueTypeRef
	 * @return List
	 */
	@SuppressWarnings("unchecked")
	public static <T> T jsonToListObject(String jsonStr, TypeReference<T> valueTypeRef){
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}
		try {
			return (T) objectMapper.readValue(jsonStr, valueTypeRef);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 将json字符串转化为泛型容器，如map
	 * @author sangshan
	 * @param jsonStr 待转化json字符串
	 * @param containerClass 容器Class类
	 * @param GenericsClasses 可变参数列表，表示容器泛型Class类
	 * @return 转化后的泛型容器
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static <T> T jsonToGenericContainer(String jsonStr, Class<?> containerClass, Class<?>... GenericsClasses)
			throws JsonParseException, JsonMappingException, IOException {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}
		if (StringUtils.isEmpty(jsonStr)) {
			return null;
		}
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(containerClass, GenericsClasses);
		return objectMapper.readValue(jsonStr, javaType);
	}

	/**
	 * 将java对象转化为JSON
	 * @param object
	 * @return jsonStr
	 */
	public static String ObjecttoJSon(Object object) {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}

		try {
			return objectMapper.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
}
